<script setup>
import { defineOptions, watch, toRef } from "vue";
import useConfigStore from "@/stores/config.js";
import { useI18n } from "vue-i18n";
//切换深色模式icon的图标
import { Sunny, Moon } from "@element-plus/icons-vue";
const { t, locale } = useI18n();
//定义组件的配置项
defineOptions({
  name: "app-config",
});

//这里的数据是写死的，不需要响应式
const lngList = [
  { title: "中文", id: "zh" },
  { title: "English", id: "en" },
];

//获取仓库配置项
const configStore = useConfigStore();


//切换语言的点击事件
function selectAction(value) {
  //修改仓库的数据
  configStore.language = value;
  //把用户的选择保存下来，持久化存储，用localStorage
  localStorage.setItem("language", value);
  //修改vue-i18n的语言配置
  locale.value = value;
}

const isDark = toRef(configStore, "isDark");

watch(
  isDark,
  //持久化存储用户的选择
  () => {
    localStorage.setItem("theme", isDark.value ? "dark" : "light");
    //修改theme
    document
      .querySelector("html")
      .setAttribute("class", isDark.value ? "dark" : "");
  },
  {
    immediate: true,
  }
);
</script>
<template>
  <div>
    <!-- 切换语言 -->
    <el-dropdown>
      <span class="el-dropdown-link">
        切换语言
        <el-icon class="el-icon--right">
          <arrow-down />
        </el-icon>
      </span>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item
            v-for="item in lngList"
            :key="item.id"
            @click="selectAction(item.id)"
          >
            <span :class="{ active: item.id === configStore.language }"
              >{{ item.title }}
            </span>
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>

    <!-- 切换深色/浅色主题 -->
    <el-switch
      v-model="configStore.isDark"
      style="margin-left: 24px"
      inline-prompt
      :active-icon="Moon"
      :inactive-icon="Sunny"
      size="small"
    />
  </div>
</template>
<style scoped>
.active {
  color: #da8;
}

:deep .el-tooltip__trigger {
  outline: none;
}
.el-dropdown-link {
  margin-top: 5px;
}
</style>
